/**
 * 
 */
package IndexComponent;

import java.io.IOException;

import PagedFile.PF_Abort_Exception;
import PagedFile.PF_FileHandle;
import PagedFile.PF_Manager;

/**
 * @author Neil
 *
 */
public class IX_Manager implements IX_Manager_Interface {
	
	PF_Manager pfm;
	
	public IX_Manager(PF_Manager pfm) {
		this.pfm = pfm;
	}

	/* (non-Javadoc)
	 * @see IndexComponent.IX_Manager_Interface#CloseIndex(IndexComponent.IX_IndexHandle)
	 */
	@Override
	public void CloseIndex(IX_IndexHandle ih) {
		ih.bptree.CloseTree();
		try {
			pfm.CloseFile(ih.bptree.pfh);
		} catch (PF_Abort_Exception pfe) {
			throw new IX_Abort_Exception(pfe.getMessage());
		}
		ih.open = false;
	}

	/* (non-Javadoc)
	 * @see IndexComponent.IX_Manager_Interface#CreateIndex(java.lang.String, int, int, int)
	 */
	@Override
	public IX_IndexHandle CreateIndex(String filename, int indexNo,
			int attrType, int attrLength) throws PF_Abort_Exception, IOException {
		
		PF_FileHandle pfh;
		try {
			pfh = pfm.CreateFile(filename + ".index"+indexNo);
		} catch(PF_Abort_Exception pfe) {
			throw new IX_Abort_Exception(pfe.getMessage());
		}
		
		// Establish and Store a new B+-Tree head.
		BPlusTree bptree = new BPlusTree(pfh, attrType, attrLength);
		
		return new IX_IndexHandle(bptree);
	}

	/* (non-Javadoc)
	 * @see IndexComponent.IX_Manager_Interface#DestoryIndex(java.lang.String, int)
	 */
	@Override
	public void DestoryIndex(String filename, int indexNo) {
		try {
			pfm.DestroyFile(filename+".index"+indexNo);
		} catch (PF_Abort_Exception pfe) {
			throw new IX_Abort_Exception(pfe.getMessage());
		}
	}

	/* (non-Javadoc)
	 * @see IndexComponent.IX_Manager_Interface#OpenIndex(java.lang.String, int)
	 */
	@Override
	public IX_IndexHandle OpenIndex(String filename, int indexNo) throws IOException {
		
		PF_FileHandle pfh = pfm.OpenFile(filename+".index"+indexNo);
		
		// Load head information from the file.
		BPlusTree bptree = new BPlusTree(pfh);
		
		// Establish a new IX_IndexHandle and return it
		return new IX_IndexHandle(bptree);
	}
}